package com.lagou.client;

import com.google.common.cache.*;
import com.google.common.collect.ImmutableMap;
import com.lagou.common.JSONSerializer;
import com.lagou.common.RpcDecoder;
import com.lagou.common.RpcEncoder;
import com.lagou.common.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.recipes.cache.*;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static org.apache.curator.utils.ZKPaths.split;

public class RpcConsumer {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static Map<String,UserClientHandler> userClientHandlerMap = new HashMap<>();

    private static Cache<String, Long> timeCache = CacheBuilder.newBuilder()
            .expireAfterWrite(5, TimeUnit.SECONDS)
            .build();

    public RpcConsumer(CuratorFramework client) throws Exception {
        final PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/server-list", true);
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        pathChildrenCache.getListenable().addListener((curatorFramework, event) -> {
            switch (event.getType()){
                case CHILD_ADDED:
                    registerClient(event.getData().getData());
                    break;
                case CHILD_REMOVED:
                    unRegisterClient(event.getData().getData());
                    break;
                default:
                    break;
            }
        });

        client.getChildren().watched().forPath("/server-list").forEach(server -> {
            try {
                byte[] bytes = client.getData().forPath("/server-list/"+server);
                registerClient(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void unRegisterClient(byte[] bytes){
        String s = new String(bytes);
        UserClientHandler userClientHandler = userClientHandlerMap.get(s);
        if (Objects.nonNull(userClientHandler)){
            userClientHandler.getEventLoopGroup().shutdownGracefully();
            userClientHandlerMap.remove(s);
            System.out.println("注销服务端："+s);
        }
    }

    private void registerClient(byte[] bytes) throws Exception {
        String s = new String(bytes);
        String[] split = s.split(":");
        String ip = split[0];
        int port  = Integer.parseInt(split[1]);
        EventLoopGroup group = new NioEventLoopGroup();
        final UserClientHandler userClientHandler = new UserClientHandler();
        userClientHandler.setEventLoopGroup(group);
        userClientHandler.setServerName(s);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect(ip, port).sync();
        userClientHandlerMap.put(s,userClientHandler);
        timeCache.put(s,0L);
        System.out.println("注册服务端："+s);
    }

    public Object createProxy(final Class<?> serviceClass){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法

                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                rpcRequest.setClassName(serviceClass.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameters(args);
                rpcRequest.setParameterTypes(method.getParameterTypes());

                if (userClientHandlerMap.isEmpty()){
                    throw new IllegalStateException("服务端未启动");
                }
                Map<String, Long> cacheMap = new HashMap<>();
                userClientHandlerMap.keySet().forEach(server -> cacheMap.put(server,Optional.ofNullable(timeCache.getIfPresent(server)).orElse(0L)));
                List<Map.Entry<String, Long>> serverList = cacheMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList());
                if (serverList.isEmpty()){
                    throw new IllegalStateException("服务端列表为空");
                }
                Long minTime = serverList.get(0).getValue();

                List<String> minTimeList = serverList.stream().filter(a -> minTime.equals(a.getValue())).map(Map.Entry::getKey).collect(Collectors.toList());
                String key;
                if (minTimeList.size() == 1){
                    key = minTimeList.get(0);
                }else {
                    key = getRandomKey(minTimeList);
                }
                System.out.println("5秒内耗时："+serverList.stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList())+"，使用服务端："+key);
                UserClientHandler next = userClientHandlerMap.get(key);
                // 设置参数
                next.setRpcRequest(rpcRequest);
                // 去服务端请求数据

                long beginTime = System.currentTimeMillis();
                Object o = executor.submit(next).get();
                long endTime = System.currentTimeMillis();
                long l = endTime - beginTime;
                timeCache.put(next.getServerName(),l);
                System.out.println("耗时："+l);
                return o;
            }
        });
    }

    private String getRandomKey(List<String> keyList) {
        int index = new Random().nextInt(keyList.size());
        return keyList.get(index);
    }


}
